package com.example.springboot.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.AuthAccess;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Documents;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.DocumentsService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/documents")
public class DocumentsController {
    @Resource
    DocumentsService documentsService;
//    @Value("${ip:localhost}")
//    String ip;
//    @Value("${server.port}")
//    String port;
//    private static final String ROOT_PATH=System.getProperty("user.dir")+File.separator+"documents";  //C:\Users\288\Desktop\Project\springboot\files
//    @PostMapping("/upload")
//    public Result upload(@RequestParam("name") String name,@RequestParam("type") String type, @RequestParam("file") MultipartFile file) throws IOException {
//        String originalFilename = file.getOriginalFilename();  //文件的原始名称
//        //aa.png
//        String mainName = FileUtil.mainName(originalFilename);    //aa
//        String extName = FileUtil.extName(originalFilename);   //png
//        if (!FileUtil.exist(ROOT_PATH)){
//            FileUtil.mkdir(ROOT_PATH);          //如果当前文件的父级目录不存在，就创建
//        }
//        if (FileUtil.exist(ROOT_PATH +File.separator+ originalFilename)){     //如果说当前上传的文件已经存在，那么这个时候我就要重命名一个文件名称
//            originalFilename = System.currentTimeMillis()+ "_" + mainName + "." + extName;
//        }
//        File saveFile = new File(ROOT_PATH + File.separator+originalFilename);
//        file.transferTo(saveFile);  //存储文件到本地的磁盘里面
//        documentsService.saveDocument(name , type);
//        String url ="http://"+ip+":"+port+"/documents/download/" +originalFilename;
//        documentsService.saveUrl(url);
//        return Result.success(url);  //返回文件的连接，这个链接就是文件下载的地址，这个下载地址就是我的后台提供出来的
//    }
//
//    @AuthAccess
//    @GetMapping("/download/{fileName}")
//    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
//        response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "UTF-8"));  // 预览
//        String filePath = ROOT_PATH + File.separator + fileName;
//        if(!FileUtil.exist(filePath)){
//            return;
//        }
//        byte[] bytes = FileUtil.readBytes(filePath);
//        ServletOutputStream outputStream = response.getOutputStream();
//        outputStream.write(bytes);  //数组是一个字节数组，也就说文件的字节流数组
//        outputStream.flush();
//        outputStream.close();
//    }
    //    新增用户信息
    @PostMapping("/add")
    public Result add(@RequestBody Documents documents){
        try {
            documentsService.save(documents);
        }catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据异常");
            }else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    //修改用户信息
    @PutMapping("/update")
    public Result update(@RequestBody Documents documents){
        documentsService.updateById(documents);
        return Result.success();
    }
    //删除用户
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        documentsService.removeById(id);
        return Result.success();
    }
    //查询全部文件
    @GetMapping("/selectAll")
    public Result selectAll(){
        List<Documents> documentsList = documentsService.list(new QueryWrapper<Documents>().orderByDesc("id"));  //select * from user order by id desc
        return Result.success(documentsList);
    }
    //批量删除
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids){
        documentsService.removeBatchByIds(ids);
        return Result.success();
    }
    //多条件分页模糊查询用户信息
    @GetMapping("/selectByPage")
    public Result selectByPage( @RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam String name,
                                @RequestParam String type){
        QueryWrapper<Documents> queryWrapper = new QueryWrapper<Documents>().orderByDesc("id");
        queryWrapper.like(StrUtil.isNotBlank(type), "type" ,type);
        queryWrapper.like(StrUtil.isNotBlank(name), "name" ,name);
        // select *from user where username like '%#{username}%' and name like '%#{name}%'
        Page<Documents> page = documentsService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }
}
